<?php
/**
 * Created by PhpStorm.
 * User: hanbin
 * Date: 17/5/31
 * Time: 上午10:32
 */

namespace App\Logic\zhihu;


use App\Logic\BaseLogic;
use App\Server\zhihu\OrderModel;
use App\Server\zhihu\ServiceModel;

class OrderLogic extends BaseLogic
{
    /**
     * 订单列表
     *
     * @param array $data
     * @return array
     */
    public static function getList($data = [])
    {
        if ($data) {
            $detail = OrderModel::getList($data['pagesize'], null, $data['last_id'], ['status' => 1, 'member_id' => $data['member_id']]);
            if ($detail) {
                $list = $detail['data'];
                if ($list) {
                    $result = [];
                    foreach ($list as $k => $v) {
                        $item = $v;
                        $serviceDetail = ServiceModel::first(['id' => $v['service_id']]);
                        if ($serviceDetail) {
                            $item['service_name'] = $serviceDetail['name'];
                        } else {
                            $item['service_name'] = '';
                        }
                        unset($item['update_time']);
                        unset($item['status']);
                        unset($item['member_id']);
                        $result[] = $item;
                    }
                    $detail['data'] = $result;
                }

            }
            return self::success($detail, 200, 'ok');
        } else {
            return self::error('请求参数有误', 206);
        }
    }

    public static function place($data = [])
    {
        if ($data) {
            $model = [];
            $model['ordertype'] = self::addOrderNumber();
            $model['service_id'] = $data['service_id'];
            $model['member_id'] = $data['member_id'];
            $orderPrice = (float)$data['orderprice'];
            $ordernumber = (int)$data['ordernumber'];
            $model['orderprice'] = $data['orderprice'];
            $model['ordernumber'] = $data['ordernumber'];
            $model['pay_status'] = 2;
            $model['status'] = 1;
            $model['update_time'] = time();
            $model['create_time'] = time();
            $model['pay_time'] = 0;
            $model['ordersum'] = $orderPrice * $ordernumber;
            $up = OrderModel::add($model);
            if ($up) {
                return self::success(['flag' => 1], 200, '下单成功');
            } else {
                return self::success(['flag' => 0], 200, '下单失败');
            }
        } else {
            return self::error('请求参数有误', 206);
        }
    }

    /**
     * 生产订单号
     * @return string
     */
    private static function addOrderNumber()
    {
        return date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

}